//the text to link code (uriaggressive) is from Kim A. Brandt. See http://userscripts.org/scripts/show/7122
 const SS_uriaggressive = /[a-z][a-z0-9+-.]*:((\/\/(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:]|%[a-f0-9]{2})*@)?((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])|([a-z0-9-\._~!$&'\(\)\/\*\+,;=]|%[a-f0-9]{2})+(:[0-9]+)?(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*)|(\/(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]+|%[a-f0-9]{2})(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*)?)|(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]+|%[a-f0-9]{2})(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*))+(\?([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@/?]|%[a-f0-9]{2})*)?(#([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@/?]|%[a-f0-9]{2})*)?/i;
 const SS_uri = /((http)s?|(ftp)|(mailto)):((\/\/(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:]|%[a-f0-9]{2})*@)?((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])|([a-z0-9-\._~!$&'\(\)\/\*\+,;=]|%[a-f0-9]{2})+(:[0-9]+)?(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*)|(\/(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]+|%[a-f0-9]{2})(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*)?)|(([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]+|%[a-f0-9]{2})(\/[a-z0-9-\._~!$&'\(\)\/\*\+,;=:@]*|%[a-f0-9]{2})*))+(\?([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@/?]|%[a-f0-9]{2})*)?(#([a-z0-9-\._~!$&'\(\)\/\*\+,;=:@/?]|%[a-f0-9]{2})*)?/i;
 
 const SS_uri2_57 = /[a-z0-9+-.(@)?]*\b\.((name)|([A-za-z]){2,3})\b([A-Za-z0-9$_+-=!*();&%/?:~.]*)?/i;
 const SS_uri2_56 = /[a-z0-9+-.(@)?]*\b\.(com|net|org|edu|uk|au)\b([A-Za-z0-9$_+-=!*();&%/?:~.]*)?/i;
 
 const SS_uri2 = /[^\.\(\)\"\s:-][a-z0-9+-.\(@\)?]*\b\.(com|org|edu|gov|net|biz|info|name|tv|uk|ca|de|jp|fr|au|us|ru|it|es|gr|no|nl|ch|hk|mil|mobi)\b(([-A-Za-z0-9$_+=&%/?:~])*([\.,*;!\(\)](?=[-A-Za-z0-9$_+=*\(\);&%/?:~]))*)*/i;
 const SS_uri2RnD2 = /[^\.\(\)\"\s:]{1,}(([a-z0-9+-.\(@\)?]+\.)*(com|org|edu|gov|net|biz|info|name|tv|uk|ca|de|jp|fr|au|us|ru|it|es|gr|no|nl|ch|hk|mil|mobi)\b(([-A-Za-z0-9$_+=&%/?:~])*([\.,*;!\(\)](?=[-A-Za-z0-9$_+=*\(\);&%/?:~]))*)*)/i;
// const SS_uri2_66 = /[^\.\(\)\"\s:][a-z0-9+-\(@\)?]*\b\.(com|org|edu|gov|net|biz|info|name|tv|uk|ca|de|jp|fr|au|us|ru|it|es|gr|no|nl|ch|hk|mil|mobi)\b(([-A-Za-z0-9$_+=&%/?:~])*([\.,*;!\(\)](?=[-A-Za-z0-9$_+=*\(\);&%/?:~]))*)*/i;
 const SS_uri2_63_1 = /(([-A-Za-z0-9$_+=()&%/?:~])*([\.,*;!@](?=[-A-Za-z0-9$_+=*();&%/?:~]))*)*\b\.(com|org|edu|gov|net|biz|info|name|tv|uk|ca|de|jp|fr|au|us|ru|it|es|gr|no|nl|ch|hk|mil|mobi)\b(([-A-Za-z0-9$_+=()&%/?:~])*([\.,*;!](?=[-A-Za-z0-9$_+=*();&%/?:~]))*)*/i;
 const SS_uri2RnD = /(([-A-Za-z0-9$_+=&%~])*([\.@](?=[A-Za-z0-9]))?)*\.(com|org|edu|gov|net|biz|info|name|tv|uk|ca|de|jp|fr|au|us|ru|it|es|gr|no|nl|ch|hk|mil|mobi)\b(([-A-Za-z0-9$_+=()&%/?:~])*([\.,*;!](?=[-A-Za-z0-9$_+=*();&%/?:~]))*)*/i;

 const SS_illegal = /^(a|button|label|legend|option|script|select|style|textarea|title)$/i;
 
 var SS_prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
 var SS_alertTimeOut = 1500;
 
 const SS_ulreplacement = "<u>$1</u>";
		  
//pref consts		
const SMACK_AUTOURL   = "extensions.swaksmack.autourl_boolpref1";  
const SMACK_EASYURL   = "extensions.swaksmack.easyurl_boolpref1";
const SMACK_MAXURL = "extensions.swaksmack.maxurl_boolpref1";
const SMACK_MAXLENGTH = "extensions.swaksmack.maxurllength_intpref";
const SMACK_TRUNCURL = "extensions.swaksmack.truncurl_stringpref";
const SMACK_OUTWITALERT = "extensions.swaksmack.outwitwarn_pref1";
const SMACK_OUTWITVOTEALERT = "extensions.swaksmack.outwitvotewarn_pref1";
const SMACK_OUTWITRANDOM = "extensions.swaksmack.outwitrandom_pref1";
const SMACK_GURUGUESSALERT = "extensions.swaksmack.guruguesswarn_pref1";
const SMACK_POLLINTERVAL = "extensions.swaksmack.pollinterval_intpref";

const SMACK_ENABLEHL = "extensions.swaksmack.enablehl_boolpref1";
const SMACK_IGNORECASEHL = "extensions.swaksmack.ignorecasehl_boolpref1";
const SMACK_IGNORESPHL = "extensions.swaksmack.ignoreselfposts_boolpref1";
const SMACK_ENABLELRHL = "extensions.swaksmack.enableinlrhl_boolpref1";
const SMACK_KEYWORDHL1 = "extensions.swaksmack.keywordshl1_stringpref";
const SMACK_TCHL1 = "extensions.swaksmack.hltextcolor1_stringpref";
const SMACK_BTCHL1 = "extensions.swaksmack.hlbkcolor1_stringpref";
const SMACK_UNDERLINEHL1 = "extensions.swaksmack.hlunderline1_boolpref1";
const SMACK_ITALICHL1 = "extensions.swaksmack.hlitalic1_boolpref1";
const SMACK_BOLDHL1 = "extensions.swaksmack.hlbold1_boolpref1";
const SMACK_CHATWILDCARD = "extensions.swaksmack.chatwildcard_boolpref1";
const SMACK_BLOCKWILDCARD = "extensions.swaksmack.blockwildcard_boolpref1";
const SMACK_OUTLINEHL1 = "extensions.swaksmack.postoutlinehl_boolpref1";
const SMACK_USERNAMEONLYHL1 = "extensions.swaksmack.usernameonlyhl_boolpref1";
const SMACK_WORDONLYHL1 = "extensions.swaksmack.wordonlyhl_boolpref1";
const SMACK_USERNAMEHL1 = "extensions.swaksmack.usernamehl1_stringpref";
const SMACK_ENABLEIGNORE1 = "extensions.swaksmack.ignore.enableignoreposts_boolpref1";
const SMACK_IGNORELIST1 = "extensions.swaksmack.ignore.ignorelist1_stringpref";
const SMACK_IGNORELIST2 = "extensions.swaksmack.ignore.ignorelist2_stringpref";
const SMACK_IGNORELISTATTEND = "extensions.swaksmack.ignore.ignorelistattend1_stringpref";
const SMACK_CHATSPEED = "extensions.swaksmack.adv.chatspeed_intpref";
const SMACK_AUDIOGLOBALENABLE = "extensions.swaksmack.audio.global_enable_boolpref";
const SMACK_AUDIOSOUND_OUTWIT = "extensions.swaksmack.audio.outwitsound_stringpref";
const SMACK_CHECKPMCHAT = "extensions.swaksmack.pmchatcheck_boolpref1";
const SMACK_ENHANCEDCHATUI = "extensions.swaksmack.enhancedChatUI_boolpref";
const SMACK_ENHANCEDCHATUIICONS = "extensions.swaksmack.enhancedChatUIIcons_boolpref";
const SMACK_ENHANCEHIDEAVATARS = "extensions.swaksmack.enhancedHideAvatars_boolpref";
const SMACK_SBSALEINTERVAL = "extensions.swaksmack.statusbarsaleinterval_intpref";
const SMACK_DISPLAYPMSTATUSBAR = "extensions.swaksmack.appearance.displaystatusbarpm_boolpref1";
const SMACK_DISPLAYLRSTATUSBAR = "extensions.swaksmack.appearance.displaystatusbarlr_boolpref1";
const SMACK_DISPLAYKWSTATUSBAR = "extensions.swaksmack.appearance.displaystatusbarkw_boolpref1";
const SMACK_DISPLAYSALESTATUSBAR = "extensions.swaksmack.appearance.displaystatusbarsale_boolpref1";
const SMACK_TINYURLENABLE = "extensions.swaksmack.tinyurl_enable_boolpref1";
const SMACK_TINYURLLENGTH = "extensions.swaksmack.tinyurl_maxurllength_intpref";
const SMACK_REPLYPREFIX = "extensions.swaksmack.replyprefix_stringpref";
const SMACK_REPLYSUFFIX = "extensions.swaksmack.replysuffix_stringpref";
const SMACK_TINYURLPREVIEW = "extensions.swaksmack.tinyurl_enablepreview_boolpref";

const SMACK_CHECKPMINTERVAL = "extensions.swaksmack.options.pmcheckinterval_intpref";

//break the prefs into option items groups
//these grouping will allow the reseting of different categories (e.g. ignore, audio,etc)
var SMACK_OPTIONITEMS = [SMACK_AUTOURL,SMACK_EASYURL,SMACK_MAXURL,SMACK_MAXLENGTH,
SMACK_TRUNCURL,SMACK_OUTWITALERT,SMACK_OUTWITVOTEALERT,SMACK_OUTWITRANDOM,SMACK_GURUGUESSALERT,
SMACK_ENABLEHL,SMACK_IGNORECASEHL,SMACK_IGNORESPHL,SMACK_ENABLELRHL,SMACK_KEYWORDHL1,
SMACK_TCHL1,SMACK_BTCHL1,SMACK_UNDERLINEHL1,SMACK_ITALICHL1,SMACK_BOLDHL1,SMACK_WORDONLYHL1,
SMACK_USERNAMEONLYHL1,SMACK_OUTLINEHL1,SMACK_USERNAMEHL1,SMACK_CHATWILDCARD,SMACK_BLOCKWILDCARD,
SMACK_CHECKPMCHAT,SMACK_CHECKPMINTERVAL,SMACK_ENHANCEDCHATUI,SMACK_TINYURLENABLE,SMACK_TINYURLLENGTH,
SMACK_SBSALEINTERVAL,SMACK_ENHANCEDCHATUIICONS,SMACK_ENHANCEHIDEAVATARS,SMACK_REPLYPREFIX,SMACK_REPLYSUFFIX,
SMACK_TINYURLPREVIEW
];

var SMACK_IGNORE_OPTIONITEMS = [SMACK_ENABLEIGNORE1,SMACK_IGNORELIST1,SMACK_IGNORELIST2,
SMACK_IGNORELISTATTEND
];

var SMACK_ADV_OPTIONITEMS = [SMACK_CHATSPEED
];

var SMACK_AUDIO_OPTIONITEMS = [SMACK_AUDIOSOUND_OUTWIT,SMACK_AUDIOGLOBALENABLE
];

var SMACK_APPEARANCE_OPTIONITEMS = [
SMACK_DISPLAYPMSTATUSBAR,SMACK_DISPLAYLRSTATUSBAR,SMACK_DISPLAYKWSTATUSBAR,SMACK_DISPLAYSALESTATUSBAR
];

//div ids used to find outwit opt in and answer elements
const SMACK_OUTWITCHATDIV = "chatPost";  // was "chat", commentInfo
const SMACK_COMMENTTEXT = "commentText";
const SMACK_COMMENTNICK = "chatNick";
const SMACK_COMMENTAVATAR = "chatAvatarContainer";
const SMACK_OUTWITCOMMENTDIV = "comment_comment";
const SMACK_PMDIV = "messagesContainer";
const SMACK_OUTWITCAPDIV = "captchaBox";
const SMACK_OUTWITANSWERDIV = "outwitAnswer";
const SMACK_OUTWITGURUGUESSDIV = "guruMakeGuess";
const SMACK_DEALDIV = "deal";
const SMACK_OUTWITCONDIV = "outwitContainer";
const SMACK_GURUCONDIV = "guruContainer";
//needed???
const SMACK_SHOWNAMEVALUE = "showName";
const SMACK_SHOWNAMEDIV = "The Daily Smack with Smack Daddy";

const SMACK_ALERT_OUTWITOPTIN = 1;
const SMACK_ALERT_OUTWITVOTE = 2;
const SMACK_ALERT_GURUGUESS = 10;

//var SS_chatcss = "@namespace url(http://www.w3.org/1999/xhtml);  /* Change color of  links */ #chat div.commentText a:visited, #chat div.commentText a:link { color: #FF7800 !important; } ";

var SS_chatcss = "@namespace url(http://www.w3.org/1999/xhtml);  /* Change color of  links */ #chat div.commentText a:visited, #chat div.commentText a:link { color: #FF7800 !important; } a.swaksmackReply { color: #FF7800 !important; font-size: 11px;} a.swaksmackHighlightUser, a.swaksmackUnhighlightUser {color: #FFBC80 !important; font-size: 11px;}  ";


var SS_outwitAlertAck = false;
var SS_outwitVoteAck = false;
//REMOVE var SS_HL_onetime = false;

var SS_chatHeaderChange = false;



var SS_ggListenerAdded = false;
var SS_guruguessAlertAck = false;
var SS_keywordDisplayLength = 15;

var SS_window;


var SS_dynamicKeywords = new Array();

var SS_combinedUsernames = new Array();

var SS_dynamicUsernames = new Array();

var SS_colorCommentMatchArray = new Array();
var SS_ChatHeaderText = null;
var SS_UID;
var SS_ggcalc;
var SS_GGCalcWindow;

//var tinyurlpreviewregex = new RegExp("tinyurl\.com\/(\.*)",ig);
var tinyurlpreviewregex = /tinyurl\.com\/(.*)/i;

const JF_HL_replacement = "\u0009\(\[^\u0009\]*\)\u0009";
var JF_HL_repRegEx = new RegExp(JF_HL_replacement,"g");
const JF_taggedMatches = "\u0009$1\u0009";	
const JF_pass2replace = "$1";

//ignore list
var JF_ignoreUserlistRegExp = null;
var JF_ignoreWordlistRegExp = null;
var JF_ignoreAttendancelistRegExp = null;

//highlight lists
var JF_keywordlistRegExp = null;
var JF_usernamelistRegExp = null;

 function checkHost(doc) {
 	 	host = doc.location.host;
 	 	//alert(host);
 	 	if (host == 'www.jellyfish.com' || host == 'jellyfish.com' || host==null || host=='')
 	 		return true;
 	 	return false;	
 }
 
 function isPMArea(doc) {

 	if (doc == null) doc=content.document;
 	var hostPath = doc.location.pathname;
 	var matches = hostPath.match("/shoppers/me/messages");
 	if (matches != null) {
 		return true;
	}
	return false;
 }
 
  function isSmackShopArea(doc) {
  	if (doc == null) doc = content.document;
 	var hostPath = doc.location.pathname;
 	var matches = hostPath.match("/smacktv/channel");
 	if (matches != null) {
 		return true;
	}
	return false;
 }
 
  function isLRArea(doc) {
  	if (doc == null) doc = content.document;
  	var lrDiv = doc.getElementById('livingRoomName');
 		if (lrDiv != null) return true;
	return false;
 }

 function chatLinkColor(doc) {
 	if (doc == null) doc = content.document;
 				var heads = doc.getElementsByTagName("head");
			if (heads.length > 0) {
				/*
				var node = doc.createElement("style");
			///	node.href="chrome://swaksmack/skin/swaksmack.css";
				node.innerHTML = SS_chatcss;
				node.type = "text/css";
				heads[0].appendChild(node); 
				*/
				var node = doc.createElement("link");
				node.href="chrome://swaksmack/skin/swaksmack.css";
				//node.innerHTML = SS_chatcss;
				node.type = "text/css";
				node.rel="Stylesheet";
				heads[0].appendChild(node);
			}
 }
 //from http://robertnyman.com/js/getElementsByClassName.js
function getElementsByClassName_ORG(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];		
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}	
	}
	return (arrReturnElements)
}

function _getElementsByXPath(expression,parent) {
    var results = [];
    var query = document.evaluate(expression, parent || window.content.document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    for (var i = 0, length = query.snapshotLength; i < length; i++)
        results.push(query.snapshotItem(i));
    return results;
};
function getElementsByClassName(className,parent) {
    var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]";
    return _getElementsByXPath(q,parent);
}

function buildClassNameRegex(strClassName) {
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	return oRegExp;
}

 function buildSearchString(searchArray, wordBoundary) {
 	if(wordBoundary == null) wordBoundary = true;
 	var searchreg = null;
 	if (searchArray == null) return searchreg;
	for (var i=0; i<searchArray.length;i++){
		if (searchArray[i] == null || searchArray[i]== "") continue;
		if (searchreg == null) {
			var trimmed = searchArray[i].replace(/^\s+|\s+$/g, '') ;
			searchreg = SS_escapeRegExLiterals(trimmed);
			//searchreg = SS_escapeRegExLiterals(searchArray[i].trim());
			if(wordBoundary) {
				var glob = /\\\*$/.test(searchreg);
				if (!glob) {
					searchreg = '\\b'+searchreg+'\\b';
					//alert('exact match ' + searchreg);
				}
				else {
					//replace \*
					searchreg = searchreg.replace(/\\\*$/,'');
				}
		}
			if (searchreg == '')
				searchreg = null;
			continue;
		}
		var trimmed = searchArray[i].replace(/^\s+|\s+$/g, '') ;
		var str = SS_escapeRegExLiterals(trimmed);
		///var str = SS_escapeRegExLiterals(searchArray[i].trim());
		if(wordBoundary) {
			var glob = /\\\*$/.test(str);
			if (!glob) {
				str = '\\b' + str + '\\b';
				//alert('exact match ' + str);
			}
			else {
				//alert('glob match ' + str);
				str = str.replace(/\\\*$/,'');
			}
		}
		if (str != null && str != '')
			searchreg = searchreg + '|' + str;
		//searchreg = searchreg + '|' +  SS_escapeRegExLiterals(searchArray[i].trim()); 
	}
	return searchreg;
 }
 
 //http://4umi.com/web/javascript/array.htm#unique
 
 function getUniqueArray(sourceArray,b) {
 var a = [], i, l = sourceArray.length;
 for( i=0; i<l; i++ ) {
  if( a.indexOf( sourceArray[i], 0, b ) < 0 ) { a.push( sourceArray[i] ); }
 }
 return a;
}

 
  function highlightExistingComments(doc) { 
 	if (doc == null) return;
 	//var firstComment = swaksmack.SS_JF.getFirstChatId();
 	//var lastComment = swaksmack.SS_JF.getLastChatId();
 	//var num = lastComment - firstComment;
 	var cm = swaksmack.SS_JF.getChatMonitor2(gBrowser.contentWindow);
 	if (cm == null) return;
 	//alert('num comments ' + num);
 		for (var i=0;i<cm.length;i++) {
 		//var index = firstComment+i;
 		var comment = 'comment' + cm[i];
 		var chatComment = doc.getElementById(comment);				
		commentColor(chatComment,doc);
				
 		//if (i==10) alert(chatComment + ' 10th ' + comment)
 	}
 }
 

 
  function highlightExistingUsernames(doc, username,highlightclass) { 
 	if (doc == null) return;
 	var cm = swaksmack.SS_JF.getChatMonitor2(gBrowser.contentWindow);
 	if (cm == null) return;
 	for (var i=0;i<cm.length;i++) {
 		var comment = 'comment' + cm[i];
 		var chatComment = doc.getElementById(comment);				
		//commentColor(chatComment,doc);
		updateHighlightLinks(doc,username,chatComment,highlightclass);

 	}
 }

 function toggleHighlightedCommentDisplay(doc,hidden) { 
 	if (doc == null || hidden == null) return;
 	var cm = swaksmack.SS_JF.getChatMonitor2(gBrowser.contentWindow);
 	if (cm == null) return;
 		for (var i=0;i<cm.length;i++) {
 		//var index = firstComment+i;
 		var comment = 'comment' + cm[i];
 		var chatComment = doc.getElementById(comment);
 		if (hidden == true) {
 			//don't hide highlighted comments
 			var sunhl = chatComment.getAttribute('swaksmackusernamehighlighted');
 			var skhl = chatComment.getAttribute('swaksmackkeywordhighlighted');
 			if (sunhl == 'true' || skhl == 'true'){
 				//alert('found comment to NOT hide');
 				continue;
 			}
 			//chatComment.style.display='none';
 			hideChatComment(chatComment, true);
 		}
 		else {
 			hideChatComment(chatComment, false);
 			//chatComment.style.display='inline';
 		}				
		//commentColor(chatComment,doc);
				
 	}
 }
 
 function hideChatComment(chatComment, hide) {
 	if (chatComment == null) return;
 	if (hide == true) {
 		chatComment.style.display='none';
 	}
 	else {
 		//chatComment.style.display='inline';
 		//var ccs = chatComment.getElementsByTagName("style");
 		chatComment.removeAttribute("style");
 		/*
 		if (ccs != null && ccs.length>0) {
 			alert(ccs[0] + ' ccs len ' + ccs.length);
 			chatComment.removeChild(ccs[0]);
 		}
 		else {
 			chatComment.style.display='inherit';
 		}
 		*/
 	}
}
 
 function initUserNameArray(clear) {
 	if (clear == null) clear=false;
 	//alert(clear + ' pre initUserNameArray SS_dynamicUsernames ' + SS_dynamicUsernames);
 	if (clear) {
 		SS_dynamicUsernames = [];
 		SS_combinedUsernames = [];
	}
 	var usernames =SS_getPreference(SMACK_USERNAMEHL1);
  if (usernames != null && usernames.length >0) {
  	var unarray = usernames.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(',');
  	SS_combinedUsernames = SS_dynamicUsernames.concat(unarray);
  }
  else {
  	//just copy the dynamicusernames
  	SS_combinedUsernames = SS_dynamicUsernames.slice();
  }
  //alert('pre unique initUserNameArray SS_dynamicUsernames ' + SS_combinedUsernames);
  SS_combinedUsernames = getUniqueArray(SS_combinedUsernames,true);
  JF_usernamelistRegExp = null;
  //alert('initUserNameArray SS_dynamicUsernames ' + SS_combinedUsernames);

}
 
 function commentEnhance(element, doc) {
 	///////////////////////
// alert(element.className + ' (cn) commentEnhance entry (id) ' +element.id);
 
  if (isLRArea(doc) == true && SS_getPreference(SMACK_ENABLELRHL) == false) {
  	//alert('ce--lr return');
 		return;
 	}
 	
 	var jellyfishstrings = document.getElementById("swaksmack-strings");
 
 //	if (true) return;
  var commentInfo = getElementsByClassName("commentInfo",element);
 	var chatNick = getElementsByClassName('chatNick',commentInfo[0]);
	var postUserName = chatNick[0].textContent;
 
  var usernames =SS_getPreference(SMACK_USERNAMEHL1);
  
  var unindex = SS_combinedUsernames.indexOf(postUserName);
  
  /*
  var unindex = -1;
  if (usernames != null && usernames.length >0) {
  	var unarray = usernames.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(',');
  	var joinedArray = SS_dynamicUsernames.concat(unarray);
    unindex = joinedArray.indexOf(postUserName);
  }
  else {
  	unindex = SS_dynamicUsernames.indexOf(postUserName);
  }
  */

  var tooltip = '';
  //alert('postUserName ' + postUserName + ' unindex ' + unindex);
 	var useImage = false;
 	try {
 		useImage = SS_getPreference(SMACK_ENHANCEDCHATUIICONS);
 	}
 	catch(x){}

 	var commentText = getElementsByClassName("commentText",element);
 //	var chatPost = getElementsByClassName("chatPost",element);
 	var link = doc.createElement("a");
 	if (unindex<0) {
 		link.className='swaksmackHighlightUser';
 		if (useImage) {
 			link.innerHTML="<img src=\"chrome://swaksmack/skin/icons/highlighter.png\"/>";
 			//link.innerHTML="<img src=\"chrome://swaksmack/skin/icons/color_swatch.png\"/>"; //class=\"swaksmackHighlightUser\"
 		}
 		else {
 			link.textContent='Highlight';
 		}
 		tooltip = jellyfishstrings.getString("highlight_tooltip");
 		link.title=tooltip;
// 		var img = doc.createElement("img");
// 		img.src="chrome://swaksmack/skin/icons/color_swatch.png";
// 		link.appendChild(img);
 		
	}
	else {
		link.className='swaksmackUnhighlightUser';
 		//link.textContent='Unhighlight';
 		if (useImage) {
 			//link.innerHTML="<img src=\"chrome://swaksmack/skin/icons/no_color_swatch.png\"/>"; //class=\"swaksmackUnhighlightUser\"
 			link.innerHTML="<img src=\"chrome://swaksmack/skin/icons/unhighlighter.png\"/>"; //class=\"swaksmackUnhighlightUser\"
 		}
 		else {
 			link.textContent='Unhighlight';
 		}
 		tooltip = jellyfishstrings.getString("unhighlight_tooltip");
 		link.title=tooltip;
 		
	}
 	link.target='_blank';
   link.href = '#';
   try{
   //commentInfo[0].appendChild(link);
   commentInfo[0].insertBefore(link,commentText[0]);
  }
  catch (x) {}

  link.addEventListener('click', enhancedHighlight,false);


			
	//insert a space		
	var txtNode = doc.createTextNode(" ");
	try{ 	
		commentInfo[0].insertBefore(txtNode,commentText[0]);	
	}
  catch (x) {}
			
  var replylink = doc.createElement("a");
 	replylink.className='swaksmackReply';
 	if (useImage) {
 		replylink.innerHTML="<img src=\"chrome://swaksmack/skin/icons/user_comment.png\"/>";
	}
	else {
 		replylink.textContent=' Reply';
 	} 		
 	tooltip = jellyfishstrings.getString("reply_tooltip");
 	replylink.title=tooltip;

 	replylink.target='_blank';
  replylink.href = '#';
   try{
   //commentInfo[0].appendChild(link);
   commentInfo[0].insertBefore(replylink,commentText[0]);
  }
  catch (x) {}
  
  replylink.addEventListener('click', enhancedReply,false);
  
  commentInfo = null;
  commentText = null;
  chatNick = null;

  	
}

function enhancedHighlight(e) {
	e.stopPropagation();
  e.preventDefault();
  
  var useImage = false;
 	try {
 		useImage = SS_getPreference(SMACK_ENHANCEDCHATUIICONS);
 	}
 	catch(x){}
	var highlightTarget = e.target;
	if (useImage) {
		highlightTarget = e.target.parentNode;
	}
		
		//alert(" event.target.parentNode.className " + highlightTarget.className);
	var ci = getCommentInfo(highlightTarget);
		
			
	//alert(pn.className + ' (org) --commentInfo element ' + ci.className);
	var chatNick = getElementsByClassName('chatNick',ci);
	var username = chatNick[0].textContent;
	//	alert('highlight user posts from ' + username);
	
//	updateHighlightLinks(username, highlightTarget);
		
		var cn = highlightTarget.className;
		//highlightExistingUsernames(swaksmack.SmackShopDoc,username,cn);
		
		/*
		var index = SS_dynamicUsernames.indexOf(username);
		if (index == -1) {
			SS_dynamicUsernames.push(username);
			initUserNameArray(false);			
		}
		
		
		
		var removeNameIndex = SS_dynamicUsernames.indexOf(username);
		//alert('remove name index ' + removeNameIndex);
		if (removeNameIndex != -1) {
			//highlightExistingComments(content.document,username);
			if (removeNameIndex == 0 ) {
				SS_dynamicUsernames.shift();
				initUserNameArray(false);
			}
			else if(removeNameIndex ==SS_dynamicUsernames.length-1){
				SS_dynamicUsernames.pop();
				initUserNameArray(false);
			}
			else {
				SS_dynamicUsernames = SS_dynamicUsernames.splice(1,removeNameIndex);
				initUserNameArray(false);
			}
			//alert('SS_dynamicUsernames after remove ' + SS_dynamicUsernames);
		}
		
		*/
		highlightExistingUsernames(content.document,username,cn);
		
		chatNick = null;
  
}

function updateHighlightLinks(doc,username, chatComment, highlightclass) {
	//alert('UHL');
	if (doc == null|| username == null || chatComment == null || highlightclass == null) return;
	if (SS_getPreference(SMACK_ENABLEHL) == false) return; 

 	
 	//var ci = getElementsByClassName('commentInfo',chatComment);
 	var htarget = getElementsByClassName(highlightclass,chatComment);
 //	alert('htarget ' + htarget);
//	var highlightTarget = htarget[0];
 	
 	var jellyfishstrings = document.getElementById("swaksmack-strings");
  var tooltip = '';
	var useImage = false;
 	try {
 		useImage = SS_getPreference(SMACK_ENHANCEDCHATUIICONS);
 	}
 	catch(x){}
	var highlightTarget = htarget[0];	
	var chatNick = getElementsByClassName('chatNick',chatComment);
	var postusername = chatNick[0].textContent;
	//alert(postusername + ' pun, hun ' + username);
	if (username != postusername) return;
	
	//alert(postusername + ' pun, hun ' + username);
		var cn = highlightclass;
		if (cn == 'swaksmackHighlightUser') {
			highlightTarget.className='swaksmackUnhighlightUser';
			//event.target.textContent='Unhighlight';
			if (useImage) {
				highlightTarget.innerHTML="<img src=\"chrome://swaksmack/skin/icons/unhighlighter.png\"/>";
				//highlightTarget.innerHTML="<img src=\"chrome://swaksmack/skin/icons/no_color_swatch.png\"/>";
			}
			else {
				highlightTarget.textContent='Unhighlight';
			}
			tooltip = jellyfishstrings.getString("unhighlight_tooltip");
 			highlightTarget.title=tooltip;
			//alert('adding user ' + username);
			
			var index = SS_dynamicUsernames.indexOf(username);
			if (index == -1) {
				SS_dynamicUsernames.push(username);
				initUserNameArray(false);			
			}
			
			if (SS_getPreference(SMACK_ENABLEHL) == true) {
				//org 090707-1 commentColor(chatComment,doc,true);
				highlightUsername(chatComment,doc);
			}
			//alert('adding user SS_dynamicUsernames ' + SS_dynamicUsernames);
		}
		else if (cn == 'swaksmackUnhighlightUser'){
			highlightTarget.className='swaksmackHighlightUser';
			//event.target.textContent='Highlight';
			if (useImage) {
				highlightTarget.innerHTML="<img src=\"chrome://swaksmack/skin/icons/highlighter.png\"/>";
				//highlightTarget.innerHTML="<img src=\"chrome://swaksmack/skin/icons/color_swatch.png\"/>";
			}
			else {
				highlightTarget.textContent='Highlight';
			}
			tooltip = jellyfishstrings.getString("highlight_tooltip");
 			highlightTarget.title=tooltip;
 			if (SS_getPreference(SMACK_ENABLEHL) == true) {
 				unhighlightUsername(chatComment,doc);
 			}
 			
 			
			var removeNameIndex = SS_dynamicUsernames.indexOf(username);
			//alert('remove name index ' + removeNameIndex);
			if (removeNameIndex != -1) {
				//highlightExistingComments(content.document,username);
				if (removeNameIndex == 0 ) {
					SS_dynamicUsernames.shift();
					initUserNameArray(false);
				}
				else if(removeNameIndex ==SS_dynamicUsernames.length-1){
					SS_dynamicUsernames.pop();
					initUserNameArray(false);
				}
				else {
					SS_dynamicUsernames = SS_dynamicUsernames.splice(1,removeNameIndex);
					initUserNameArray(false);
				}
				//alert('SS_dynamicUsernames after remove ' + SS_dynamicUsernames);
			}
			
		}
		
		chatNick = null;
}


function enhancedReply(e) {
	//alert('enhanced reply ' + e.target);
	e.stopPropagation();
  e.preventDefault();
 
  try {
  	var useImage = SS_getPreference(SMACK_ENHANCEDCHATUIICONS);

	  //alert(e.target.parentNode + " event.target.className " + e.target.className);
	 	
	 	var replyTarget = e.target;
		if (useImage) {
			replyTarget = e.target.parentNode;
		}
  	
  	//alert("replyTarget.className " + replyTarget.className);
	  var ci = getCommentInfo(replyTarget);
	 // alert('reply commentInfo ' + ci);
	  var chatNick = getElementsByClassName('chatNick',ci);
		var username = chatNick[0].textContent;
	//	 alert('reply username ' + username);
	
			
		var chatPrefix ='';
		if (chatNick != null && chatNick[0] != null) {
			//alert( ' reply to ' + username);
		//	var cpost = swaksmack.SmackShopDoc.getElementById('comment_comment');
			var cpost = content.document.getElementById('comment_comment');
			var replyText = getBrowserSelection();
	
	    if (replyText != null && replyText.length>0) {
	    	replyText = "\""+replyText+"\"";
	    }
	    else {
	    	replyText = '';
	    }
			    
	
		  cpost.value = buildReply(username,replyText);
			cpost.focus();
			}
		}
	catch(x){}
}

function previewTinyURL(element, doc, turl, commentDiv) {
	//alert(' previewTinyURL ' + element.textContent);
	if (element == null || doc == null || turl == null || commentDiv == null) return;
	var commentPosts = getElementsByClassName("chatPost",commentDiv);
	var chatPost = commentPosts[0];
	var commentTexts = getElementsByClassName(SMACK_COMMENTTEXT,chatPost);
	//var preview = 'preview';
	
	var useImage = false;
	try {
		useImage = SS_getPreference(SMACK_ENHANCEDCHATUIICONS);
	}
	catch(x){}
	var jellyfishstrings = document.getElementById("swaksmack-strings");
	var tooltip = '';
	var previewlink = doc.createElement("a");
	previewlink.className = 'swaksmacktinyurlpreview';
	//alert('PTU previewlink created, comment text ' + commentTexts[0].textContent);
	turl = turl.replace(/tinyurl\.com/,"preview.tinyurl.com");
	previewlink.href = turl;
	if (useImage) {
		previewlink.innerHTML="<img src=\"chrome://swaksmack/skin/icons/monitor_link.png\"/>";
	}
	else {
		previewlink.textContent = '(preview)';
	}
	tooltip = jellyfishstrings.getString("tinyurl_preview_tooltip");
	previewlink.title = tooltip;
	         
   //_TEST
   ///073107 link.href = element.nodeValue;
   previewlink.rel="external";
   
 // commentTexts[0].appendChild(previewlink);
 // element.parentNode.insertBefore(previewlink, element);
 //insert after 
 //	element.parentNode.insertBefore(previewlink, element.nextSibling);
 	
 	element.parentNode.parentNode.insertBefore(previewlink, element.parentNode.nextSibling);
  
  //element.appendChild(previewlink); // TEXT TO LINK
  //alert('previewlink added');
	var space = doc.createTextNode(' ');
	element.parentNode.parentNode.insertBefore(space, previewlink);

 
}

function buildReply(username,replytext) {
	//alert('buildReply ' + username);
	if (username == null) return '';
	var prefix = SS_getPreference(SMACK_REPLYPREFIX); 
	var suffix = SS_getPreference(SMACK_REPLYSUFFIX);
	var reply = prefix + username;
	if (replytext != null && replytext != '')
		reply = reply + " " + replytext + suffix + ' ';
	else
		reply = reply + suffix + ' ';
	return reply;
	
}

function highlightUsername(element, doc) {
  if (isLRArea(doc) == true && SS_getPreference(SMACK_ENABLELRHL) == false) {
		return;
 	}
 	//alert('unhighlight');
 	var highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL1);
 	var outlinePost = SS_getPreference(SMACK_OUTLINEHL1);
 	var commentPosts = getElementsByClassName("chatPost",element);
	var chatPost = commentPosts[0];
	var bkgrdColor = SS_getPreference(SMACK_BTCHL1);
  var outlinePost = SS_getPreference(SMACK_OUTLINEHL1);
  var highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL1);
  var chatNick = getElementsByClassName(SMACK_COMMENTNICK,chatPost);
  
	if (highlightUsernameOnly) {
		//just highlight username
		var bkgrdColor = SS_getPreference(SMACK_BTCHL1);
		chatNick[0].style.background = bkgrdColor;
		var textColor = SS_getPreference(SMACK_TCHL1);
		chatNick[0].style.color = textColor;			
	}
	else if (!outlinePost) {
		var bkgrdColor = SS_getPreference(SMACK_BTCHL1);
		chatPost.style.background = bkgrdColor;
		var textColor = SS_getPreference(SMACK_TCHL1);
		chatPost.style.color = textColor;
	}
  
  if (outlinePost == true) {   
		chatPost.style.border='3px solid ' + bkgrdColor;
	}

		

	//if (highlightUsernameOnly == true) {	
	//}
 		//alert('usernamematch pre prop add');
 	//element.swaksmackusernamehighlighted = true;
 	element.setAttribute('swaksmackusernamehighlighted',true);
 	if (swaksmack.smackCommentsHidden == true) {
 		//alert('hide uhl post');
 		hideChatComment(element, false);
 	}
 		//alert('element.swaksmackusernamehighlighted added ' + element.swaksmackusernamehighlighted);
 	
}

function unhighlightUsername(element, doc) {
  if (isLRArea(doc) == true && SS_getPreference(SMACK_ENABLELRHL) == false) {
		return;
 	}
 	//alert('unhighlight');
 	var highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL1);
 	var outlinePost = SS_getPreference(SMACK_OUTLINEHL1);
 	var commentPosts = getElementsByClassName("chatPost",element);
	var chatPost = commentPosts[0];
	chatPost.style.border='none';
	chatPost.style.background = 'inherit';
	chatPost.style.color = 'inherit';
		
	var chatNick = getElementsByClassName(SMACK_COMMENTNICK,chatPost);
	//if (highlightUsernameOnly == true) {
		//reset to original
		//chatNick[0].style.background ='#062037';
		chatNick[0].style.background = 'inherit';
		chatNick[0].style.color ='#FF7800';
	//}
 		//alert('usernamematch pre prop add');
 	//element.swaksmackusernamehighlighted = false;
 	element.setAttribute('swaksmackusernamehighlighted',false);
 	if (swaksmack.smackCommentsHidden == true) {
 		//alert('hide uhl post');
 		hideChatComment(element, true);
 	}
 		//alert('element.swaksmackusernamehighlighted added ' + element.swaksmackusernamehighlighted);
 	
}

 function commentColor(element, doc,un) {
 	///////////////////////
  if (un == null) un = false;
  if (isLRArea(doc) == true && SS_getPreference(SMACK_ENABLELRHL) == false) {
 		return;
 	}
	if (un == true) {
		//alert('commentColor username call');
	}
	
	//element.setAttribute('swak','mindstorm360');
	element.setAttribute('swaksmackusernamehighlighted',false);
	element.setAttribute('swaksmackkeywordhighlighted',false);
 	
 	
 	var keywords = SS_getPreference(SMACK_KEYWORDHL1);
	var usernames =SS_getPreference(SMACK_USERNAMEHL1);
	var ignorePostsEnabled= SS_getPreference(SMACK_ENABLEIGNORE1);
	var ignorelist =SS_getPreference(SMACK_IGNORELIST1);
	var ignorelist2 = SS_getPreference(SMACK_IGNORELIST2);
	var ignorelistattend = SS_getPreference(SMACK_IGNORELISTATTEND);
	var chatwildcardmatch = SS_getPreference(SMACK_CHATWILDCARD);
	var blockwildcardmatch = SS_getPreference(SMACK_BLOCKWILDCARD);
	var ignoreSelfPosts = SS_getPreference(SMACK_IGNORESPHL);
	var hideAvatar = SS_getPreference(SMACK_ENHANCEHIDEAVATARS);
	
	var userMuted = false;
	
  var commentPosts = getElementsByClassName("chatPost",element);
	var chatPost = commentPosts[0];
  if (chatPost == null)  {
  	//user may be muted
  	commentPosts = getElementsByClassName("chatPostMuted",element);
  	chatPost = commentPosts[0];
  	if (chatPost != null) {
  		userMuted = true;
  	}
  	else {
  		//chat post not found at all
  		return;
  	}
  } 
  
	var commentTexts = getElementsByClassName(SMACK_COMMENTTEXT,chatPost);
	var chatNick = getElementsByClassName(SMACK_COMMENTNICK,chatPost);  //"chatNick" "chatAvatarContainer"
	if (commentTexts == null || chatNick == null) return;
	
	if (hideAvatar) {
		var chatAvatar = getElementsByClassName('chatAvatar',chatPost);  //"chatNick" "chatAvatarContainer"
		chatAvatar[0].style.display='none';
	}
	
	
	if (ignoreSelfPosts) {
		var nickname = swaksmack.SS_JF.getNickName();
	//	alert(chatNick[0].textContent + ' chatnick, ignore self nn ' + nickname);
		if (chatNick[0].textContent == nickname) return;
	}
	
	if (ignorePostsEnabled) {
		//check post against ignore list
		if (ignorelist != null && ignorelist != "") {
			if (JF_ignoreUserlistRegExp == null) {
				ignorelist = ignorelist.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(','); // Allow for spaces in usernames
				ignorelist = buildSearchString(ignorelist,blockwildcardmatch);
				//ending with a | or , can be bad
				ignorelist = ignorelist.replace(/(\|$)|(,$)/,'');
				
				JF_ignoreUserlistRegExp = new RegExp(ignorelist,"ig");
			}
			
			//alert(usernames);
			//var ignorelistRegExp = new RegExp(ignorelist,"ig");
	  	var ignoreListMatch = isUsernameMatch(chatNick[0],JF_ignoreUserlistRegExp);
	  	if (ignoreListMatch) {
	  		chatPost.style.display='none';
	  		return;
	  	}
		}
		
		if (ignorelist2 != null && ignorelist2 != "") {
			if (JF_ignoreWordlistRegExp == null) {
				ignorelist2 = ignorelist2.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(','); // Allow for spaces in usernames
				ignorelist2 = buildSearchString(ignorelist2,blockwildcardmatch);
				//ending with a | or , can be bad
				ignorelist2 = ignorelist2.replace(/(\|$)|(,$)/,'');
				//alert(usernames);
				JF_ignoreWordlistRegExp = new RegExp(ignorelist2,"ig");
			}
			
			var it = commentTexts[0].textContent;
			var ignoreListMatch = JF_ignoreWordlistRegExp.test(it);
	  	//var ignoreListMatch = isUsernameMatch(chatNick[0],ignorelistRegExp);
	  	if (ignoreListMatch) {
	  		//alert('ignoring post based on keyword');
	  		chatPost.style.display='none';
	  		return;
	  	}
		}
		if (ignorelistattend != null && ignorelistattend != "") {
			if (JF_ignoreAttendancelistRegExp == null) {
				//alert(' attendignorelistupdate ' + JF_ignoreAttendancelistRegExp);
				ignorelistattend = ignorelistattend.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(','); // Allow for spaces in usernames
				ignorelistattend = buildSearchString(ignorelistattend, false);
				//ending with a | or , can be bad
				ignorelistattend = ignorelistattend.replace(/(\|$)|(,$)/,'');
				//allow for leading and trailing white space
				ignorelistattend = "^\\s*(" +ignorelistattend +")\\s*$";
				JF_ignoreAttendancelistRegExp = new RegExp(ignorelistattend,"ig");
			}
			
			//alert('ignorelistRegExp ' + ignorelistRegExp);
			var it = commentTexts[0].textContent;
			var ignoreListMatch = JF_ignoreAttendancelistRegExp.test(it);
	  	//var ignoreListMatch = isUsernameMatch(chatNick[0],ignorelistRegExp);
	  	if (ignoreListMatch) {
	  		//alert('ignoring attendance post ' + it);
	  		chatPost.style.display='none';
	  		return;
	  	}
		}		
	}
	
	
 	var chatRegExp = null;
 	if (JF_keywordlistRegExp == null) {
 		//alert('build updated keywrod regexp');
  
 			//TODO --refactor this into something a bit cleaner
 			var searchFound = false;
 			if (keywords != null && keywords.length >0) {
 	 			keywords = keywords.replace(' ,',',').replace(', ',',').replace(/' '/g,'\s').split(','); // Allow for spaces in usernames
 				keywords = buildSearchString(keywords, chatwildcardmatch);
 				searchFound = true;
 			}
 	 		if (SS_dynamicKeywords != null && SS_dynamicKeywords.length >0) {
 	 			var dwords = buildSearchString(SS_dynamicKeywords, chatwildcardmatch);
 	 	//		alert('dwords pre cat ' + dwords);
 	 			if (keywords != null && keywords.length >0) keywords = keywords + '|' + dwords;
 	 			else keywords = dwords;
 	 			searchFound = true;
 	 		}
 			
 			//only build regex if we have something to build--otherwise things go very bad
			if (searchFound == true) {
				
				keywords = keywords.replace(/(\|$)|(,$)/g,'');

				keywords = '(' + keywords + ')';
				if(SS_getPreference(SMACK_IGNORECASEHL) == true) JF_keywordlistRegExp = new RegExp(keywords,"ig");  //was ig
				else JF_keywordlistRegExp = new RegExp(keywords,"g"); //was "g"
			}
		}

		
		searchFound = false;
		
		var keywordMatch = false;
		var userNameMatch = false;
		var highlightUsernameOnly = SS_getPreference(SMACK_USERNAMEONLYHL1);
		var highlightKeywordsOnly = SS_getPreference(SMACK_WORDONLYHL1);
		var outlinePost = SS_getPreference(SMACK_OUTLINEHL1);
		if (JF_keywordlistRegExp != null) {
			keywordMatch = colorByComment(commentTexts[0],JF_keywordlistRegExp, highlightKeywordsOnly);
		}
		
		//ad a tag to indicate that post has been highlighted
		if (keywordMatch == true) {
			//element.swaksmackkeywordhighlighted = true;
			element.setAttribute('swaksmackkeywordhighlighted',true);
			//alert(element.id + " element.swaksmackkeywordhighlighted true " +element.swaksmackkeywordhighlighted);
		}

if (JF_usernamelistRegExp == null) {
	//alert('rebuild usernamelist');
 	 	if (SS_combinedUsernames != null && SS_combinedUsernames.length >0) {
			var dwords = buildSearchString(SS_combinedUsernames, chatwildcardmatch);
			usernames = dwords;
			searchFound = true;
		}
		//if (un == true) alert('searchFound ' + searchFound);
	 	if (searchFound) {
	 		usernames = usernames.replace(/(\|$)|(,$)/,'');
			//alert(usernames);
			JF_usernamelistRegExp = new RegExp(usernames,"ig");
	  	//userNameMatch = colorByUsername(chatNick[0],JF_usernamelistRegExp);
	 	}
	}
	
	if (JF_usernamelistRegExp != null) {
		userNameMatch = colorByUsername(chatNick[0],JF_usernamelistRegExp);
	}
 	
 	if (userNameMatch == true) {
 		//element.swaksmackusernamehighlighted = true;
 		element.setAttribute('swaksmackusernamehighlighted',true);
 		//alert(element.id + ' element.swaksmackusernamehighlighted added ' + element.swaksmackusernamehighlighted);
 	}	
 	
 	if (swaksmack.smackCommentsHidden == true && keywordMatch == false && userNameMatch == false) {
 		hideChatComment(element, true);
 	}
 	else {
 		hideChatComment(element, false);
 	}
	

		

		if (keywordMatch == true && highlightKeywordsOnly == false && !outlinePost) {
				var bkgrdColor = SS_getPreference(SMACK_BTCHL1);
				//chatPost.style.background='#'+ bkgrdColor;
				chatPost.style.background = bkgrdColor;
				var textColor = SS_getPreference(SMACK_TCHL1);
				//chatPost.style.color='#'+ textColor;
				chatPost.style.color = textColor;
				updateStatusbarKeyword(5);
				return;
		}
		
		//if matched on username, highlight entire post
		if (userNameMatch) {
			if (highlightUsernameOnly) {
				//just highlight username
				var bkgrdColor = SS_getPreference(SMACK_BTCHL1);
				chatNick[0].style.background = bkgrdColor;
				var textColor = SS_getPreference(SMACK_TCHL1);
				chatNick[0].style.color = textColor;			
			}
			else if (!outlinePost) {
				var bkgrdColor = SS_getPreference(SMACK_BTCHL1);
				chatPost.style.background = bkgrdColor;
				var textColor = SS_getPreference(SMACK_TCHL1);
				chatPost.style.color = textColor;
			}
		}
		
		if (userNameMatch || keywordMatch) {
			if (outlinePost) {
				var bkgrdColor = SS_getPreference(SMACK_BTCHL1);
				chatPost.style.border='3px solid ' + bkgrdColor;
				//alert('border outline applied');
			}
			updateStatusbarKeyword(5);
		}
		
		
}

function updateStatusbarKeyword(c) {
	if (swaksmack.SS_SBM == null) {
		return;
	}
	swaksmack.SS_SBM.flashKeywordButton(c);
}
 
    function colorByComment(element, oRegExp, highlightKeywords) {
 	if (element == null || oRegExp == null) return false;
 	if (highlightKeywords == null) highlightKeywords = false;
 	var underlineMatch = SS_getPreference(SMACK_UNDERLINEHL1);
	var matches;
	var inputText = element.textContent;

	var matchFound = false;
 	
 		//fix href links and so that we don't try to color/underline--will break link			
 	var badToColor = element.getElementsByTagName("a");	

 				//alert('regex ' + oRegExp);	
	while ((matches = oRegExp.exec(inputText)) != null) {
		
		matchFound = true;
		if (underlineMatch == false && highlightKeywords == false) break;
		//for now don't attempt to color/underline as the innerhtml replace will destroy the hrefs
		if (badToColor != null && badToColor[0] !=null) break;
		
					
		var text = matches[0];
		
		var lastKWMatchIndex = SS_colorCommentMatchArray.indexOf(text);
		if (lastKWMatchIndex != -1) {
			continue;

		}
		//alert(oRegExp + ' (regex) matches: ' + matches);
		//alert('matched regex ' + oRegExp);

		 SS_colorCommentMatchArray.push(text);
		 var regextext = SS_escapeRegExLiterals(text);


	//create a group that will define $1 in the regex
		regextext = '(' +regextext + ')';

		//need to build a new regex for the matched text since multiple words in the text may match
		var mRegExp = new RegExp(regextext,"g");
		//alert(mRegExp + ' mRegExp');


		//tag the found keyword(s) by wrapping them in some char we hope we never seen in a chat post
	  //var taggedMatches = "\u0009$1\u0009";	
		element.textContent = element.textContent.replace(mRegExp, JF_taggedMatches);
					
	}
	
	//now replace the tagged matched words for underlined/highlighted words
	if (matchFound && (underlineMatch || highlightKeywords)) {
		// <([^>]*)>
		
		//replace tagged words wrapped in the UID
		//opps--uid of numbers messes up numbers in posts
		//var replacement = "#" + SS_UID + "#\(\[^#" + SS_CUID + "#\]*\)#" + SS_CUID + "#";	
		//var replacement = "<\(\[^>\]*\)>";	
		//var replacement = "\u0009\(\[^\u0009\]*\)\u0009";
		//var repRegEx = new RegExp(replacement,"g");
		
		var pass2replace = "$1";
		if (underlineMatch == true) {
			pass2replace = SS_ulreplacement;
		}
	
		if (highlightKeywords == true) {
			pass2replace = '<span style=\"color:' + SS_getPreference(SMACK_TCHL1) +';background:' + SS_getPreference(SMACK_BTCHL1) + '\">' + pass2replace + '</span>';
		}
	
		//replace all the tagged words in one replace of the innerhtml
		element.innerHTML = element.innerHTML.replace(JF_HL_repRegEx, pass2replace);

	}
	
	SS_colorCommentMatchArray = [];
	return matchFound;

 }
 
 function isUsernameMatch(element, oRegExp) {
 	if (element == null || oRegExp == null) return false;
 	var matchFound = false;
 	var matches = oRegExp.exec(element.textContent);
		if (matches != null) {
			matchFound = true;
			// draws box around username element.style.border='2px solid #ccc';
		}
		return matchFound;
 }
 
 function processSmackHero(commentDiv, doc) {
 	if (commentDiv == null || doc == null) return;
 		var largeBadge = getElementsByClassName("largeBadge",commentDiv);
 		if (largeBadge == null || largeBadge[0] == null) return;
 		var imgs = largeBadge[0].getElementsByTagName("img");
 		var shimg = null;
 		for (var i=0;i<imgs.length;i++) {
 			var alt = imgs[i].alt;
 			if (alt == 'Smack Hero') {
 				shimg = imgs[i];
 				break;
 			}
 		}
 		if (shimg == null) {
 			return;
 		}

 		var link = doc.createElement("a");
 		link.href = 'http://smackshopping.com';
	  link.rel="external";
	  var tooltip = '';
	  var jellyfishstrings = document.getElementById("swaksmack-strings"); 
	  tooltip = jellyfishstrings.getString("smackhero_link_tooltip");	
	  link.title=tooltip;
	  shimg.parentNode.insertBefore(link, shimg);
	  link.appendChild(shimg); // TEXT TO LINK
 	
	}
 
 function colorByUsername(element, oRegExp) {
 	if (element == null || oRegExp == null) return false;
 	var matchFound = false;
 	var matches = oRegExp.exec(element.textContent);
		if (matches != null) {
			matchFound = true;
			// draws box around username element.style.border='2px solid #ccc';
		}
		return matchFound;
 }
 
 function executePMLink(commentDiv, doc) {
 	if (doc == null) doc = content.document;
 	var chatDiv = doc.getElementById(commentDiv);
  var elements = doc.evaluate(".//text()", chatDiv, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
  if (elements == null) return;
  for (var i = 0; i < elements.snapshotLength; i++) textToLink(elements.snapshotItem(i), doc);
 }
 
 function execute(commentDiv, bool_highlight, doc)
 {
 	//alert('execute ' +commentDiv.className);
  if (doc == null) return;
  if (commentDiv == null) return;
  if (commentDiv.id == null || commentDiv == 'undefined') return;
 	if (bool_highlight == null) bool_highlight = true;
 
 	var elements = doc.evaluate(".//text()", commentDiv, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
 	for (var ii = 0; ii < elements.snapshotLength; ii++) textToLink(elements.snapshotItem(ii), doc,commentDiv);

	if (SS_getPreference(bool_highlight == true && SMACK_ENABLEHL) == true) {
			commentColor(commentDiv,doc);
	}
	
	if (SS_getPreference(SMACK_ENHANCEDCHATUI) == true) {
		commentEnhance(commentDiv,doc);
		processSmackHero(commentDiv,doc);
	}
		

 }

 function textToLink(element, doc, commentDiv)
 {
     if (element.parentNode.tagName.match(SS_illegal)) return;
     var generousMatch = SS_getPreference(SMACK_EASYURL);
     var matches = element.nodeValue.match(SS_uri);
     if (matches != null) {
	     var text = matches[0];
	     var index = element.nodeValue.indexOf(text);
	     if (index == 0)
	     {
	         if (element.nodeValue.length > text.length) textToLink(element.splitText(text.length), doc, commentDiv);
	         var link = doc.createElement("a");
	         //TEST for fixing link ref that have puncuation on the end
	         var newurl = element.nodeValue.replace(/([\.!,;:\*()]*)$/i,'');
	         newurl = newurl.replace(/[a-z0-9]*\.{2,}/,'');
	         link.href = newurl;
	         
	         //_TEST
	         ///073107 link.href = element.nodeValue;
	         link.rel="external";
	         element.parentNode.insertBefore(link, element);
	         link.appendChild(element); // TEXT TO LINK
	         //if (SS_getPreference(SMACK_TINYURLPREVIEW) && newurl.indexOf('http://tinyurl.com/') != -1) {
	         if (SS_getPreference(SMACK_TINYURLPREVIEW) && tinyurlpreviewregex.test(newurl)) {
	         	var tufound = tinyurlpreviewregex.test(newurl);
	         	//alert('tufound ' + tufound);
	         	//alert('element parentNode nex sibling ' + element.parentNode.nextSibling);
	         	previewTinyURL(element, doc, newurl, commentDiv);
	         	//alert('element text content ' + element.textContent);
	        }
	         slimFastUrl(element); 
		     }
		     else textToLink(element.splitText(index), doc, commentDiv);
  	 }
  	 else if (generousMatch == true){
  	 	matches = element.nodeValue.match(SS_uri2);
  	 	if (matches != null) {
	     var text = matches[0];
	     var emailFound = false;
	     if (text.indexOf("@") != -1) emailFound = true;
	     var index = element.nodeValue.indexOf(text);
	     if (index == 0)
	     {
	         if (element.nodeValue.length > text.length) textToLink(element.splitText(text.length), doc, commentDiv);
	         var link = doc.createElement("a");
	         var newurl = element.nodeValue.replace(/^([\.!,;:\*()]*)/i,'');
	          newurl = newurl.replace(/[a-z0-9]*\.{2,}/,'');
	         //link.href = 'http://'+element.nodeValue;
	         link.href = 'http://'+ newurl;
	         if (emailFound == true) {
	         	link.href = 'mailto:'+newurl;
	         }
	         link.rel="external";
	         element.parentNode.insertBefore(link, element);
	         link.appendChild(element); // TEXT TO LINK
	         	
	         if (SS_getPreference(SMACK_TINYURLPREVIEW) && tinyurlpreviewregex.test(newurl)) {
	         	//var tufound = tinyurlpreviewregex.test(newurl);
	         	//alert('tufound ' + tufound);
	         	//alert('element parentNode nex sibling ' + element.parentNode.nextSibling);
	         	previewTinyURL(element, doc, link.href, commentDiv);
	         	//alert('element text content ' + element.textContent);
	        }    
	         slimFastUrl(element);       	
		     }
		     else textToLink(element.splitText(index), doc, commentDiv);
  	 }
  	 }

 }
 
 function slimFastUrl(element){
 	  if(element == null) return;
 	  var trimUrlLength = SS_getPreference(SMACK_MAXURL);
 	  if (trimUrlLength == false) return;
 	  var maxUrlLength = SS_getPreference(SMACK_MAXLENGTH);
 	  if (maxUrlLength <=0) {
 	  	var jellyfishstrings = document.getElementById("swaksmack-strings");
 	  	var error = jellyfishstrings.getString("maxUrlLengthError1");	
 	  	alert(error);
 	  	//var defPrefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService.getDefaultBranch());
 	  	var defPrefs = SS_prefs.getDefaultBranch('extensions.swaksmack.');
			maxUrlLength = defPrefs.getIntPref('maxurllength_intpref');
			SS_prefs.setIntPref(SMACK_MAXLENGTH, maxUrlLength);
 	  }
 	  var clippedUrlEnd=SS_getPreference(SMACK_TRUNCURL);
 	  if (maxUrlLength > 0 && element.nodeValue.length > maxUrlLength){
	 		var replacelength = element.nodeValue.length;
	 		var l1 = clippedUrlEnd.length;
	 		if (l1 == maxUrlLength) l1=0;
			var front = element.substringData(0, maxUrlLength-l1);
			front = front+clippedUrlEnd;
			var tn = document.createTextNode(front);				 
			element.parentNode.replaceChild(tn,element.parentNode.firstChild);
	}
 }
 
 function externalLinks(doc) {
 	if (doc == null) doc = content.document;
 if (!doc.getElementsByTagName) return;
 var anchors = doc.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
 }
}

function commentSpellCheck(doc) {
	if (doc == null) doc = content.document;
	var commentdiv = doc.getElementById(SMACK_OUTWITCOMMENTDIV);
	if (commentdiv != null) {
		commentdiv.spellcheck = true;
	}
}

function registerSmackChatListeners(doc) {
	var chatDiv = doc.getElementById('chat');

	if (chatDiv != null){
		chatDiv.addEventListener('DOMNodeInserted', smackChatPostInserted, false);
		chatDiv.addEventListener('DOMAttrModified', smackChatPostAttrModified, false);
		chatDiv.addEventListener('DOMNodeRemoved', smackChatPostRemoved, false);
	}
	
	var guru=doc.getElementById('guruContainer');
	if (guru != null){
		guru.addEventListener('DOMAttrModified',smackChatGuruAttrModified,false);
	}
	var chatHeader = doc.getElementById('chatHeader');
	if (chatHeader != null) {
		chatHeader.addEventListener('dblclick', function(event) {
			toggleChat();
		}, false);
	}
	
	
	var msgCenterDiv = doc.getElementById('leftPanel');

	if (msgCenterDiv != null){
		
		if (SS_getPreference(SMACK_ENHANCEHIDEAVATARS))		 {	
			msgCenterDiv.addEventListener('DOMNodeRemoved', function(event) {
								//alert('DOMNodeRemoved ' + event.target.id);
								
				if (SS_getPreference(SMACK_ENHANCEHIDEAVATARS))		 {
					var state = swaksmack.SS_JF.getState();
					if (state== SMACK_STATE_OUTWITRESULT || state == SMACK_STATE_OUTWITVOTE || state == SMACK_STATE_OUTWIT_VOTED || state == SMACK_STATE_NONGURUDEALSOLD) {	
						//alert('DNR hide images');
				  	hideAllAvatarImages();
					}
				}
			}, false);
		}
		
	}
	
	var e1=doc.getElementsByName('user_guess');
	var guruinput;
	for (var i=0;i<e1.length;i++) {
	 	if (e1[i].name == 'user_guess') {
	 		guruinput = e1[i];
	 		//alert('AVL gg user guess found');
	 		break;
		}
	}
	//alert('init guruinput');
	if (guruinput != null) {
		if (SS_ggListenerAdded == false) {
			SS_ggListenerAdded = true;
			guruinput.addEventListener('dblclick', function(event) {
				//alert('launchCalcWindow');
			launchCalcWindow();
				//	alert(document.defaultView.liveObject);
				//	alert(window["liveObject"].duration);
			}, true);
		}
	}
	else {
		SS_ggListenerAdded = false;
	}
	
	
}

function smackChatPostAttrModified(event) {
	if (swaksmack.smackchatIdArray == null || swaksmack.SmackShopDoc == null) {
		return;
	}
	//alert('smackChatPostAttrModified');
	//need to to proces the last added chat comment
	var processed = false;
	while (swaksmack.smackchatIdArray.length >0) {
		//alert('smackChatPostAttrModified');
		execute(swaksmack.smackchatIdArray.pop(), true, swaksmack.SmackShopDoc);
		externalLinks(swaksmack.SmackShopDoc);
		if (processed == true) continue;
		
		if (swaksmack.SS_SBM.isMonitoring() == false) {
			swaksmack.SS_SBM.monitorState(SS_getPreference(SMACK_SBSALEINTERVAL));
		}
		setChatSpeed();
		SS_oldState = swaksmack.alertManager.state;
		swaksmack.alertManager.updateAlertState(swaksmack.SmackShopDoc);
		
		//setTimeout("smackPoll()",SS_alertTimeOut);
		smackPoll();
		if (SS_ChatHeaderText != null ) {
			//var chatHeader = swaksmack.SmackShopDoc.getElementById('chatHeader');
			//reset chatHeader content
			if (SS_chatHeaderChange == true && swaksmack.SS_JF.isChatPaused() == false) {
				//alert('header change');
				//chatHeader.innerHTML = SS_ChatHeaderText;
				updateChatHeader(true);
			}
			
		}
		processed = true;
	}
	
	

}

function smackChatPostInserted(event) {
	if (swaksmack.smackchatIdArray == null || swaksmack.SmackShopDoc == null) {
		return;
	}
	
	var cn = event.target.className;
	var id = event.target.id;
	if (id == null || id == 'undefined') {
		return;
	}
	
	if (cn != null && (cn == 'commentFloatContainer' || cn == 'swaksmackUnhighlightUser' || cn =='swaksmackHighlightUser' || cn == 'swaksmackReply')) {
		return;
	}
	//alert("Dominsert target " + event.target);
	//setChatSpeed();
	
	while (swaksmack.smackchatIdArray.length >0) {execute(swaksmack.smackchatIdArray.pop(), true, swaksmack.SmackShopDoc);}
	
	
	swaksmack.smackchatIdArray.push(event.target);
	
	/*
	SS_oldState = swaksmack.alertManager.state;
	swaksmack.alertManager.updateAlertState(swaksmack.SmackShopDoc);
	
	setTimeout("smackPoll()",SS_alertTimeOut);
	if (SS_ChatHeaderText != null ) {
		//var chatHeader = swaksmack.SmackShopDoc.getElementById('chatHeader');
		//reset chatHeader content
		if (SS_chatHeaderChange == true && swaksmack.SS_JF.isChatPaused() == false) {
			alert('header change');
			//chatHeader.innerHTML = SS_ChatHeaderText;
			updateChatHeader(true);
		}
		
	}
	*/
	
}

//shared by both smack chat and LR
function smackChatPostRemoved(event) {
	var cid = event.target.id;
	if (cid != null) {
		var cin = cid.indexOf('comment');
		if (cin != -1) {
			//alert(cin + ' comment removed ' + cid);
			var hl = getElementsByClassName('swaksmackHighlightUser',event.target);
			if (hl != null && hl[0] != null) {
				hl[0].removeEventListener('click', enhancedReply,false);
				hl[0].removeEventListener('click', enhancedHighlight,false);
				//alert(cin + ' comment hl/reply events removed ' + hl[0].className);
			}
			var uhl = getElementsByClassName('swaksmackUnhighlightUser',event.target);
			if (uhl != null && uhl[0] != null) {
				uhl[0].removeEventListener('click', enhancedReply,false);
				uhl[0].removeEventListener('click', enhancedHighlight,false);
				//alert(cin + ' comment uhl/reply events removed ' + uhl[0].className);
			}
		}
		else {
			//alert(cin + ' element removed ' + cid);
		}
	}
}

function smackChatGuruAttrModified(event) {
	if (swaksmack.alertManager == null) {
		return;
	}
	swaksmack.alertManager.updateAlertState();
}

function registerLivingRoomChatListeners(doc) {
	var chatDiv = doc.getElementById('chat');

		if (chatDiv != null){
			chatDiv.addEventListener('DOMNodeInserted', livingRoomChatPostInserted, false);
			chatDiv.addEventListener('DOMAttrModified', livingRoomChatPostAttrModified, false);
			chatDiv.addEventListener('DOMNodeRemoved', smackChatPostRemoved, false);
		}
	
}

function livingRoomChatPostInserted(event) {
	if (swaksmack.smackLRIdArray == null || swaksmack.LivingRoomDoc == null) {
		return;
	}
	
	var cn = event.target.className;
	var id = event.target.id;
	if (id == null || id == 'undefined') {
		return;
	}
	
	if (cn != null && (cn == 'commentFloatContainer' || cn == 'swaksmackUnhighlightUser' || cn =='swaksmackHighlightUser' || cn == 'swaksmackReply')) {
		return;
	}
	
	while (swaksmack.smackLRIdArray.length >0) {execute(swaksmack.smackLRIdArray.pop(), true, swaksmack.LivingRoomDoc);}
	
	
	swaksmack.smackLRIdArray.push(event.target);
	
}

function livingRoomChatPostAttrModified(event) {
	if (swaksmack.smackLRIdArray == null || swaksmack.LivingRoomDoc == null) {
		return;
	}
	//need to to proces the last added chat comment
	while (swaksmack.smackLRIdArray.length >0) {
		execute(swaksmack.smackLRIdArray.pop(), true, swaksmack.LivingRoomDoc);
		externalLinks(swaksmack.LivingRoomDoc);
		setChatSpeed();
	}
}

function checkGuruGuess() {
	//if (doc == null) doc = content.document;
	///////////////////

	var e1=swaksmack.SmackShopDoc.getElementsByName('user_guess');
	if (e1 != null) {
   		var guruinput;
   		for (var i=0;i<e1.length;i++) {
   		 	if (e1[i].name == 'user_guess') {
   		 		guruinput = e1[i];
   		 		//alert('AVL gg user guess found');
   		 		break;
   			}
   		}
   		if (guruinput != null) {
   			 if (SS_ggListenerAdded == false) {
		   		//	alert('GG add event list' + SS_ggListenerAdded);
		   			SS_ggListenerAdded = true;
		   			guruinput.addEventListener('dblclick', function(event) {
						launchCalcWindow();
							}, true);
				}
   		} else {
   			SS_ggListenerAdded = false;
   			//alert('guruinput NOT found, unable to perform calculations.SS_ggListenerAdded = false; ' + );
    	}
    		 
   	} //end e1
   	else {
   		//alert('SS_ggListenerAdded set to false');
   		SS_ggListenerAdded = false;
   	}
					
	////////////////////
		
			
	if (SS_guruguessAlertAck == false && swaksmack.SmackShopDoc.getElementById(SMACK_OUTWITGURUGUESSDIV) != null) {
	//	alert(SS_guruguessAlertAck + ' (SS_guruguessAlertAck) checkGuruGuess found GG (div) ' + SS_doc.getElementById(SMACK_OUTWITGURUGUESSDIV));
		var guruguessAlertPref = SS_getPreference(SMACK_GURUGUESSALERT);
		//alert('guruguessAlertPref ' + guruguessAlertPref);
		SS_guruguessAlertAck = true;

		if (guruguessAlertPref == "audio" || guruguessAlertPref == "both"){
			//alert('play audio');
			var soundFile = SS_getPreference(SMACK_AUDIOSOUND_OUTWIT);
			if (soundFile == null || soundFile == '') {
				soundFile = AUDIO_DIR + DEFAULT_SOUND;
			}
			swaksmack.audioManager.playAudioAlert(soundFile);
		}
		if (guruguessAlertPref == "alert" || guruguessAlertPref == "both"){
			//alert('show GG alert entered');
			var jellyfishstrings = document.getElementById("swaksmack-strings");
			var alert3 = jellyfishstrings.getString("guruguessWarn1");	
			//alert(alert3 +'\n'+Date());
			var leftPanel = swaksmack.SmackShopDoc.getElementById('leftPanel');
			if (leftPanel != null) {
				leftPanel.addEventListener('click',  function(event) { 
					swaksmack.alertManager.alertWindow.close();
					//remove this event listener 
					this.removeEventListener('click',arguments.callee,false);
				}, false);
			}
			swaksmack.alertManager.swakAlert(SMACK_ALERT_GURUGUESS, true, 60000, true);
		} else if (swaksmack.SmackShopDoc.getElementById(SMACK_OUTWITGURUGUESSDIV) == null) {
			SS_guruguessAlertAck = false;
		}
	}
	else {
		//this constantly entered during a SD show after guess is in
		//alert(SS_guruguessAlertAck + ' (SS_guruguessAlertAck) checkGuruGuess failed to find GG (div) ' + SS_doc.getElementById(SMACK_OUTWITGURUGUESSDIV));
	}
}

var SS_oldState = null;
function smackPoll() {
	//hideAllAvatarImages();
	var cState = swaksmack.alertManager.state;
	if (cState != SS_oldState) {
		swaksmack.SS_SBM.monitorState(SS_getPreference(SMACK_SBSALEINTERVAL));
	}
	if (cState == SMACK_STATE_CONTEST_END || cState == SMACK_STATE_DEAL || cState == SMACK_STATE_GG_DEAL) {
		SS_outwitAlertAck = false;
		SS_outwitVoteAck = false;
		SS_guruguessAlertAck = false;
		return;
	}
	//another safety check since we don't have a real state machine to eval transistions
	if (SS_oldState == SMACK_STATE_DEAL && cState == SMACK_STATE_OW_OPTIN) {
		SS_outwitAlertAck = false;
		SS_outwitVoteAck = false;
		SS_guruguessAlertAck = false;
	}
	/*
	if (cState == SS_oldState) {
		return;
		
	}
	else {
		alert(SS_oldState + ' (old) diff state (new) ' + cState);
	}
	*/
	var outwitAlertPref = "none";
	var outwitVoteAlertPref = "none";
	var guruguessAlertPref = "none";
	try {
 		outwitAlertPref = SS_getPreference(SMACK_OUTWITALERT);
 		outwitVoteAlertPref = SS_getPreference(SMACK_OUTWITVOTEALERT);
 		guruguessAlertPref = SS_getPreference(SMACK_GURUGUESSALERT);
	}
	catch(Exception){}
	
	
	if (cState == SMACK_STATE_OW_OPTIN){
	
		
		if (outwitAlertPref == "both" || outwitAlertPref == "alert" || outwitAlertPref == "audio") {
			//alert('opt in state');
			if (SS_outwitAlertAck == false) {
				//alert('opt in state ack false--should get opt in alert');
				SS_outwitAlertAck = true;
				if (outwitAlertPref == "both" || outwitAlertPref == "audio"){
					var soundFile = SS_getPreference(SMACK_AUDIOSOUND_OUTWIT);
					if (soundFile == null || soundFile == '') {
						soundFile = AUDIO_DIR + DEFAULT_SOUND;
					}
					swaksmack.audioManager.playAudioAlert(soundFile);
					//playAudioAlert(DEFAULT_SOUND);
				}
				if (outwitAlertPref == "both" || outwitAlertPref == "alert"){
					//var jellyfishstrings = document.getElementById("swaksmack-strings");
					//var alert1 = jellyfishstrings.getString("outwitWarn1");
					//alert(alert1+'\n'+Date());
					var capans = swaksmack.SmackShopDoc.getElementById('captcha_answer');
					if (capans != null) {
						capans.addEventListener('click',  function(event) { 
							swaksmack.alertManager.alertWindow.close();
							//remove this event listener 
							this.removeEventListener('click',arguments.callee,false);
						}, false);
					}
					
					swaksmack.alertManager.swakAlert(SMACK_ALERT_OUTWITOPTIN, true, 60000, true);
				}
			}
		}
	}
	else if (cState == SMACK_STATE_OW_VOTE){		
		if (outwitVoteAlertPref == "both" || outwitVoteAlertPref == "alert" || outwitVoteAlertPref == "audio") {
			if (SS_outwitVoteAck == false) {
				SS_outwitVoteAck = true;
				if (outwitVoteAlertPref == "both" || outwitVoteAlertPref == "audio") {
					var soundFile = SS_getPreference(SMACK_AUDIOSOUND_OUTWIT);
					if (soundFile == null || soundFile == '') {
						soundFile = AUDIO_DIR + DEFAULT_SOUND;
					}
					swaksmack.audioManager.playAudioAlert(soundFile);					
					//playAudioAlert(DEFAULT_SOUND);
				}
				if (outwitVoteAlertPref == "both" || outwitVoteAlertPref == "alert") {
					var leftPanel = swaksmack.SmackShopDoc.getElementById('leftPanel');
					if (leftPanel != null) {
						leftPanel.addEventListener('click',  function(event) { 
							swaksmack.alertManager.alertWindow.close();
							//remove this event listener 
							this.removeEventListener('click',arguments.callee,false);
						}, false);
					}
					swaksmack.alertManager.swakAlert(SMACK_ALERT_OUTWITVOTE, true, 60000, true);
				}
			}
		}
	}
	else if (cState == SMACK_STATE_GG){
		//alert('REMOVE check guru state smack poll state ' + cState);
		checkGuruGuess();
	}
	/*
	else {
		SS_outwitAlertAck = false;
		SS_outwitVoteAck = false;
		SS_guruguessAlertAck = false;
	}
	*/
}

function hideAllAvatarImages() {
	
	var ha = "/img/shoppers/avatars/.*";
	var regExp = new RegExp(ha,"ig");
	//alert(SS_doc + ' hideAllAvatarImages ' + regExp);
	var img = null;
	for(i=swaksmack.SmackShopDoc.images.length-1;i>=0;i--){
		img = swaksmack.SmackShopDoc.images[i];
		var isrc = swaksmack.SmackShopDoc.images[i].src;
		if (isrc != null && img.style.display != 'none') {
			var hide = regExp.test(isrc);
			if (hide) {
				//alert('hide ' + img.id);
				//SS_doc.images[i].src='';
				img.style.display='none';
			}
		}
		
	}
	swaksmack.SmackShopDoc.close();

}

// swaksmack context menu stuff

function swakContextVisibilityOn() {
	var menuitems = ['swaksmack-context-menu',
				'contextmenu-addkeywords',
				'contextmenu-listkeywords',
				'contextmenu-clearkeywords',
				'contextmenu-chatdisplayhl'];
	for (var i=menuitems.length-1;i>=0;i--){
		document.getElementById(menuitems[i]).setAttribute('hidden','false');
	}
}

function swakContextShowing() {
	//alert('contextShowing');
  var menuitem = document.getElementById("contextmenu-addkeywords");
  if (gContextMenu.isTextSelected) {
      var keyword;
	  if (gContextMenu.searchSelected)
			keyword = gContextMenu.searchSelected();
		else
			keyword = getBrowserSelection();
      if (keyword.length > SS_keywordDisplayLength) 
		keyword = keyword.substr(0,SS_keywordDisplayLength-1) + "...";
      var displaytext = "Add \"" + keyword + "\" to SwakSmack highlights.";
      menuitem.setAttribute("label", displaytext);
      menuitem.setAttribute("hidden","false");
  }
  else {
  	menuitem.setAttribute("hidden","true");
  }
}

function chatAddKeywords() {
	//alert('Do keyword stuff');
		var keyword = "";
	if (gContextMenu.onTextInput) 
	{
		//alert('Do keyword stuff on textinput');
		keyword = document.popupNode;
		keyword = keyword.value.substring(keyword.selectionStart, keyword.selectionEnd);
		if (keyword.length>SS_keywordDisplayLength) 
			keyword = keyword.substr(0,SS_keywordDisplayLength-1);
	}
		else 
	{
		if (gContextMenu.searchSelected)
			keyword = gContextMenu.searchSelected();
		else
			keyword = getBrowserSelection();
		if (keyword.length == 0)
		{
			//do nothing? /?an alert?
			return;
		}
	}
	if (keyword.length>0)
	{
		//alert(keyword);
		SS_dynamicKeywords.push(keyword);
		JF_keywordlistRegExp = null;
		JF_usernamelistRegExp = null;
		highlightExistingComments(content.document);
	}

	}
	
	function toggleDisplayHighlighted() {
		/*
		if(SS_HL_onetime == false) {
					//alert('should only happen once');
			SS_HL_onetime = true;
			highlightExistingComments(swaksmack.SmackShopDoc);
		}
		*/
		if (isSmackShopArea(content.document)) {
			swaksmack.smackCommentsHidden = !swaksmack.smackCommentsHidden;
			toggleHighlightedCommentDisplay(content.document,swaksmack.smackCommentsHidden);
			updateDisplayHighlightedUI(content.document);
		}
		//for now no show highlight only in LR
		/*
		else if (isLRArea(content.document)) {
			swaksmack.lrCommentsHidden = !swaksmack.lrCommentsHidden;
			toggleHighlightedCommentDisplay(content.document,swaksmack.lrCommentsHidden);
			updateDisplayHighlightedUI(content.document);

		}
		*/
		
		
	}
	
	function updateDisplayHighlightedUI(doc) {
		if (doc == null) return;
		if (isSmackShopArea(doc) && gBrowser.contentWindow == swaksmack.smackShopContentWindow) {
			var sbitem = document.getElementById('ss-sb-pu-chatdisplayhl');
			if (sbitem != null) {
				sbitem.setAttribute('checked',swaksmack.smackCommentsHidden);
			}
			var cmitem = document.getElementById('contextmenu-chatdisplayhl');
			if (cmitem != null) {
				cmitem.setAttribute('checked',swaksmack.smackCommentsHidden);
			}
			SS_chatHeaderChange = true;
			updateChatHeader(!swaksmack.SS_JF.isChatPaused());
	//		alert('smack set check hidden ' + hidden);
		}
		//for now no show highlight only in LR
		/*
		else if (isLRArea(doc) && gBrowser.contentWindow != swaksmack.smackShopContentWindow) {
			var sbitem = document.getElementById('ss-sb-pu-chatdisplayhl');
			if (sbitem != null) {
				sbitem.setAttribute('checked',swaksmack.lrCommentsHidden);
			}
			var cmitem = document.getElementById('contextmenu-chatdisplayhl');
			if (cmitem != null) {
				cmitem.setAttribute('checked',swaksmack.lrCommentsHidden);
			}
		//	alert('lr set check hidden ' + hidden);
		}
		*/
		

	}
	
	function chatClearKeywords(){
		//clear the dynamic keywords ad usernames
		//keywords specified in options are kept
		SS_dynamicKeywords = [];
		SS_dynamicUsernames = [];
		initUserNameArray(true);
		JF_keywordlistRegExp = null;
		JF_usernamelistRegExp = null;
	}

	function chatListKeywords(){
		//list keywords
		var words = SS_getPreference(SMACK_KEYWORDHL1);
		//alert('chatListKeywords SS_dynamicUsernames ' + SS_dynamicUsernames);
		var usernames = SS_combinedUsernames.join(', ');
		var list = 'SwakSmack Keywords\n';
		if (words != null && usernames != null) {
			list = list + '\nMain Keywords: \n';
			if (usernames != null) list = list + 'Usernames: ' + usernames +'\n';
			if (words != null) list = list + 'Keywords: ' + words +'\n';		
		}
		if (SS_dynamicKeywords !=null && SS_dynamicKeywords.length>0) {
			list = list + '\nDynamic Keywords: \n' +  SS_dynamicKeywords.toString();
		}
		
		alert(list);
	}	
	
	function toggleChat() {
		//alert('togglechat');
		if( isSmackShopArea(content.document) == false) {
			return;
		}
		var paused = swaksmack.SS_JF.toggleChat();
		//alert('paused ' + paused);
	//	var menuitem = document.getElementById("contextmenu-togglechat");
		var chatHeader = swaksmack.SmackShopDoc.getElementById('chatHeader');
		if (SS_ChatHeaderText == null || SS_ChatHeaderText == '') {
	 		SS_ChatHeaderText = chatHeader.innerHTML;
		}
		SS_chatHeaderChange = true;
		updateChatHeader();
		//flag it again so thatthe status updates on the next post
		//this will return the header to normal
		SS_chatHeaderChange = true;
		return paused;
	}
	
	function updateChatHeader(resume) {
		if (swaksmack.SmackShopDoc == null || swaksmack.SS_JF == null) return;
		var chatHeader = swaksmack.SmackShopDoc.getElementById('chatHeader');
		if (chatHeader == null) return;
		if (SS_ChatHeaderText == null || SS_ChatHeaderText == '') {
	 		SS_ChatHeaderText = chatHeader.innerHTML;
		}
		if (resume == null) resume = false;
		var menuitem = document.getElementById("contextmenu-togglechat");
		var paused = swaksmack.SS_JF.isChatPaused();
		if (paused) {
			chatHeader.style.color = '#FF7800';
			menuitem.setAttribute("label",SS_getStringTableText("chat_resume"));
			var chatMsg = SS_getStringTableText("chat_paused1");
			chatHeader.innerHTML = SS_ChatHeaderText + "<b> : " + chatMsg+ "</b>";
		}
		else if (resume == false) {
			chatHeader.style.color = '#FF7800';
			menuitem.setAttribute("label",SS_getStringTableText("chat_pause"));
			var chatMsg = SS_getStringTableText("chat_resume1");
			var rn = SS_getRandomNumber(5);
			
			chatMsg = (rn <= 5)?SS_getStringTableText("chat_resume"+rn) : "chat_resume1";			
			
	  	chatHeader.innerHTML = SS_ChatHeaderText + "<b> : " + chatMsg+ "</b>";
			
		}
		else {
			chatHeader.innerHTML = SS_ChatHeaderText;
		}
		
		
		if (swaksmack.smackCommentsHidden == true) {
			chatHeader.style.color = '#FF7800';
			var chatHidden = SS_getStringTableText('chat_header_display_hl_only');
			chatHeader.innerHTML = chatHeader.innerHTML + ' -- ' + chatHidden;
		}
		/*
		else {
			chatHeader.innerHTML = SS_ChatHeaderText;
		}
		*/
		SS_chatHeaderChange = false;
	}
	
	function chatReply(event, pn) {
	//alert(pn.id + ' (popnode.id) chatReply element classname ' + pn.className);
	//alert(' chatReply element parentnode ' + pn.parentNode.className);
	
	//selction
	var replyText = '';
	
			if (gContextMenu.searchSelected)
			replyText = gContextMenu.searchSelected();
		else
			replyText = getBrowserSelection();
    if (replyText.length>0) {
    	replyText = "\""+replyText+"\"";
    }
		
		
		//selection
	
	
	var ci = getCommentInfo(pn);
	//alert(pn.className + ' (org) --commentInfo element ' + ci.className);
	var chatNick = getElementsByClassName('chatNick',ci);
	
	
	var chatPrefix ='';
	if (chatNick != null && chatNick[0] != null) {
		var cpost = content.document.getElementById('comment_comment');
		cpost.value = buildReply(chatNick[0].textContent,replyText);
		cpost.focus();
	}
}

function getCommentInfo(commentNode) {
	try {
	if (commentNode == null) return null;
	if (commentNode.className == 'commentInfo') return commentNode;
	else if (commentNode.className == 'commentText') return commentNode.parentNode;
  else if (commentNode.className == 'chatNick') return commentNode.parentNode;
  else if (commentNode.className == 'chatGuru') return commentNode.parentNode;
  else if (commentNode.className == 'chatTime') return commentNode.parentNode;
  else if (commentNode.className == 'swaksmackHighlightUser') return commentNode.parentNode;
  else if (commentNode.className == 'swaksmackUnhighlightUser') return commentNode.parentNode;
  else if (commentNode.className == 'swaksmackReply') return commentNode.parentNode;
  else if (commentNode.className == 'chatAvatar') {
  	//not as straightforward, but navigation is simple
  	//find chatPost and then commentInfo
  	//alert('chatAvatar class found, parent parent parent className ' + commentNode.parentNode.parentNode.parentNode.className);
  	var cChatPost = commentNode.parentNode.parentNode.parentNode;
  	//minor recursion to find info from chatPost
  	return getCommentInfo(cChatPost);
  }
  else if (commentNode.className == 'chatPost') {
  		//the 3rd child of the chat post is the commentinfo
  	var ci = commentNode.childNodes[2];
  	if (ci != null && ci.className == 'commentInfo') {
  		return ci;
  	}
  	return null;
  }
  else {
  	//alert('unhandled commentNode.className ' + commentNode.className);
  	 return null;
  	}	
  	return null;
  }
  catch (Exception){
  	return null;
  }
}

function setChatSpeed() {
	try {
		var speed = SS_getPreference(SMACK_CHATSPEED);
		swaksmack.SS_JF.setChatSpeed(speed);
	}
	catch (Exception) {}
}

function onPMUpdate(prevPM, pmValue, prevChat, chatValue) {
	//alert(pmValue+ ' onPMUpdate ' + chatValue);
	//if there is change, update the main smack page and any current page indicator
	if (pmValue != prevPM) {
		var pmAlert = swaksmack.SmackShopDoc.getElementById('alertEnvelope');
		var contextAlert = content.document.getElementById('alertEnvelope');
		if (pmValue == true) {
			pmAlert.className = '';
			if (contextAlert != null && contextAlert != 'undefined') contextAlert.className = '';
			swaksmack.SS_SBM.setPMStatusOn();
		}
		else {
			pmAlert.className = 'noNew';
			if (contextAlert != null && contextAlert != 'undefined') contextAlert.className = 'noNew';
			swaksmack.SS_SBM.setPMStatusOff();
		}
	}
	if (chatValue != prevChat) {
		var chatAlert= swaksmack.SmackShopDoc.getElementById('alertChat');
		contextAlert = content.document.getElementById('alertChat');
		if (chatValue == true) {
			chatAlert.className = '';
			if (contextAlert != null && contextAlert != 'undefined') contextAlert.className = '';
			swaksmack.SS_SBM.setLRStatusOn();
		}
		else {
			chatAlert.className = 'noNew';
			if (contextAlert != null && contextAlert != 'undefined') contextAlert.className = 'noNew';
			swaksmack.SS_SBM.setLRStatusOff();
		}
	}
}



//guru guess calc
function launchCalcWindow() {
	if (SS_GGCalcWindow == null || SS_GGCalcWindow.closed == true) {

 		SS_GGCalcWindow=window.open('chrome://swaksmack/content/ggcalc.xul','SwakSmack Guru Calculator','height=400,width=500');

	}
	else {
		//we close and then create a new window because some of the elements 
		//the popup depends on are replaced whem the liveconatinerobject has
		//its innherhtml updated
	 	SS_GGCalcWindow.close();

 		SS_GGCalcWindow=window.open('chrome://swaksmack/content/ggcalc.xul','SwakSmack Guru Calculator','height=400,width=500');
 		

	}

	
	//create popup object--revisit
 	if ( SS_ggcalc == null) {
		SS_ggcalc = new GGCalc();
 	}
 	SS_ggcalc.popup=SS_GGCalcWindow;
}

function SS_onOptionsUpdate() {
	//alert('SS_onOptionsUpdate');
	initUserNameArray(false);
}

var swaksmack = {
		jfdoc:null,
		SS_SBM:null,
		SS_JF:null,
		SmackShopDoc:null,
		LivingRoomDoc:null,
		alertManager:null,
		audioManager:null,
		smackchatIdArray:null,
		smackLRIdArray:null,
		smackShopContentWindow:null,
		smackCommentsHidden: false,
		lrCommentsHidden: false,
		ignoreListCurrent: false,
	setdoc: function(d) {
		  swaksmack.jfdoc = d;
		},
  onLoad: function() {
    // initialization code
    this.initialized = true;
    this.strings = document.getElementById("swaksmack-strings");
    document.getElementById("contentAreaContextMenu")
            .addEventListener("popupshowing", function(e) { this.showContextMenu(e); }, false);
    //add onload listener for web pages        
    var appcontent = document.getElementById("appcontent");   // browser
    if(appcontent) {
      appcontent.addEventListener("load", this.onPageLoad, true);  
      appcontent.addEventListener("load", this.showContextMenu, true);   
      //test
      appcontent.addEventListener("unload", this.onPageUnload, true);     
    }
    
    SwakPrefWatcher.init();

          
  },
  onPageLoad: function(aEvent) {
     var doc = aEvent.originalTarget; // doc is document that triggered "onload" event
    // do something with the loaded page.
    // doc.location is a Location object (see below for a link).
    // You can use it to make your code executed on certain pages only.
   
    	/*
    if (window.title == window.opener.content.document.SS_GGCalcWindow.title) {
    	alert('GGCalc loaded');
    }
    */
  
    if (checkHost(doc) == true) {
    	//alert('onpageload');
    	//create a UID for this session
    		var d = new Date();
				SS_UID = d.getTime();
				
			if (swaksmack.SS_JF == null) {
    		swaksmack.SS_JF = new JellyFish();
    	}
				
			swaksmack.smackLRIdArray = new Array();
    	
    	var shoppingArea = false;
    	shoppingArea = isSmackShopArea(doc)
    	//store doc ref for smack shopping document
    	if (shoppingArea == true) {
    		//alert('smack area found');
    		swaksmack.SmackShopDoc = doc;
	    	//SS_doc = doc;
	    	//window.SS_doc = doc;
	    	SS_window = window;
				swaksmack.smackShopContentWindow = gBrowser.contentWindow;
	    	swaksmack.smackchatIdArray = new Array();
    	  registerSmackChatListeners(swaksmack.SmackShopDoc);
    	  updateDisplayHighlightedUI(swaksmack.SmackShopDoc);
    	
    }
    
    //enable for offline guruguess test
    if (false) {
	    //temp for gg calc test
	    swaksmack.SmackShopDoc = doc;
	    registerSmackChatListeners(swaksmack.SmackShopDoc);
  	}
    
    	//check to see if in the private message area
    	
    	
    	if (isPMArea(doc) == true) {
    		executePMLink(SMACK_PMDIV, doc);
    		return;
    	}
    	else if (isLRArea(doc) == true) {
    		swaksmack.LivingRoomDoc = doc;
    		registerLivingRoomChatListeners(swaksmack.LivingRoomDoc);
    		updateDisplayHighlightedUI(swaksmack.LivingRoomDoc);
    	}
    //	alert('onpageload');
    	commentSpellCheck(doc);
    	chatLinkColor(doc);
    	
			initUserNameArray(false);



    	//registerChatListeners(doc);
    	//register listener on the chat post for tinyurl
    	registerChatPostListener(doc);
    	//SS_AM = new SSAlertManager();
    	if (swaksmack.alertManager == null)
    		swaksmack.alertManager = new SSAlertManager();
    	if (swaksmack.audioManager == null)	
    		swaksmack.audioManager = new AudioManager();

			swaksmack.SS_SBM.setKWStatusConnected();
			if (shoppingArea == true) {
				swaksmack.SS_SBM.monitorState(SS_getPreference(SMACK_SBSALEINTERVAL));
			}
			else {
				//alert('not shopping area');
			}
		  
		 // SS_SBM.hideStatusBar(true);
			
			if (SS_getPreference(SMACK_CHECKPMCHAT) == true) {
				var jfc = new JellyFishPMChecker();
				jfc.setInterval(SS_getPreference(SMACK_CHECKPMINTERVAL));
				jfc.checkPM();
			}
    	
    	//menu stuff
    	  
    	  var menu = document.getElementById("contentAreaContextMenu");
    	  //alert(menu);
  			menu.addEventListener("popupshowing", swakContextShowing, false);
  			swakContextVisibilityOn();
  			
  			//http://developer.mozilla.org/en/docs/Code_snippets:Tabbed_browser#Closing_a_tab
  			var container = gBrowser.tabContainer;
				container.addEventListener("TabClose", swaksmack.tabRemoved, false);
				container.addEventListener("TabSelect", swaksmack.tabSelected, false);
				//container.addEventListener("TabClose", function(e) { alert('af tab removed'); }, false);
				
				if (SS_getPreference(SMACK_ENHANCEHIDEAVATARS)) {	
			  	hideAllAvatarImages();
				}
				
				
				swaksmack.setdoc(doc);
			
    }
  },
  onPageUnload: function(aEvent) {
  	try {
	  	var doc = aEvent.originalTarget;
	  	//var doc = aEvent.target;
	  	var	host = doc.location.host;
	  	if (swaksmack.smackShopContentWindow == gBrowser.contentWindow) {
	  	//var doc = aEvent.originalTarget;
		  	if (checkHost(doc) == true && isSmackShopArea(doc)) {
					swaksmack.updateConnectedStatus(aEvent);	
					swaksmack.SS_SBM.stopMonitorState();
		  	}
		  	updateDisplayHighlightedUI(swaksmack.SmackShopDoc);
		  	swaksmack.dispose();
	  	}
  	}
  	catch(x){}
  	
  	
  },
  showContextMenu: function(event) {
    // show or hide the menuitem based on what the context menu is on
    // see http://kb.mozillazine.org/Adding_items_to_menus
    //document.getElementById("context-jellyfish").hidden = gContextMenu.onImage;  //org
    document.getElementById("context-swaksmack").hidden = !checkHost();
  },
  onMenuItemCommand: function(e) {
  	
  	//no longer needed for chat/url processing --remove menu item???
  	//execute(SMACK_OUTWITCHATDIV);
  	//externalLinks();

                                
  },
  tabRemoved: function(event) {
  	try {
  		var browser = event.target.linkedBrowser;
	  	//alert('jf tab removed ' + event.originalTarget);
	  	var doc = content.document;
	  	if (swaksmack.smackShopContentWindow == browser.contentWindow) {
	  		//alert('browser.contentWindow is ss contwindow');
		  	if (checkHost(doc) == true && isSmackShopArea(doc)) {
		  		swaksmack.updateConnectedStatus(event);
		  		swaksmack.SS_SBM.stopMonitorState();
		  	}
		  	updateDisplayHighlightedUI(swaksmack.SmackShopDoc);
		  	swaksmack.dispose();
	  	}
  	}
  	catch(x){}
  	
  	
  },
  dispose: function() {
  	swaksmack.smackShopContentWindow = null;
		swaksmack.smackCommentsHidden = false;
  	swaksmack.smackchatIdArray = [];
  	JF_ignoreUserlistRegExp = null;
 		JF_ignoreWordlistRegExp = null;
 		JF_ignoreAttendancelistRegExp = null;
		JF_keywordlistRegExp = null;
		JF_usernamelistRegExp = null;
  },
  tabSelected: function(event) {
  	try {
  		
  		updateDisplayHighlightedUI(content.document);
  		//alert('tabselected updated display UI');
  	}
  	catch (x){}
  },
  updateConnectedStatus: function(event) {
		//alert(' swak updateConnectedStatus ');
		if (swaksmack.SS_SBM == null)
			swaksmack.SS_SBM = new StatusBarManager();
		swaksmack.SS_SBM.setKWStatusDisabled();
		swaksmack.SS_SBM.setSaleStatusDisconnected();
  		
  	
  },
  getUserGuess: function() {
  	if (swaksmack.SmackShopDoc == null) return null;
  	//alert('ss testdoc' + swaksmack.testdoc);
  	return  swaksmack.SmackShopDoc.getElementsByName('user_guess');
  }

};

var SwakPrefWatcher = {
	prefs: null,
	init: function() {
		this.prefs = Components.classes["@mozilla.org/preferences-service;1"]
         .getService(Components.interfaces.nsIPrefService)
         .getBranch("extensions.swaksmack.");
    this.prefs.QueryInterface(Components.interfaces.nsIPrefBranch2);
    this.prefs.addObserver("", this, false);    
    this.initStatusBar();
    this.initAudio();

    
	},
	initStatusBar: function() {
		if (swaksmack.SS_SBM == null) {
     	//SS_SBM = new StatusBarManager();
     	swaksmack.SS_SBM = new StatusBarManager();
     	var sb1 = document.getElementById('swak-sb-kw-status');
			swaksmack.SS_SBM.setKWStatusBarPanel(sb1);
			
			var sbpm = document.getElementById('swak-sb-pm-status');
		  swaksmack.SS_SBM.setPMStatusBarPanel(sbpm);
		  
		  var sblr = document.getElementById('swak-sb-lr-status');
		  swaksmack.SS_SBM.setLRStatusBarPanel(sblr);
		  
		  var sbsale = document.getElementById('swak-sb-sale-status');

			swaksmack.SS_SBM.setSaleStatusBarPanel(sbsale);
    }
    var hid = this.prefs.getBoolPref("appearance.displaystatusbarpm_boolpref1");
    swaksmack.SS_SBM.hidePM(!hid);
    
    hid = this.prefs.getBoolPref("appearance.displaystatusbarlr_boolpref1");
    swaksmack.SS_SBM.hideLR(!hid);
    
    hid = this.prefs.getBoolPref("appearance.displaystatusbarkw_boolpref1");
    swaksmack.SS_SBM.hideKW(!hid);
    
    hid = this.prefs.getBoolPref("appearance.displaystatusbarsale_boolpref1");
    swaksmack.SS_SBM.hideSale(!hid)
	},
	initAudio: function() {
		var audio = document.getElementById('ss-sb-pu-audio');
		var enabled = this.prefs.getBoolPref("audio.global_enable_boolpref");
		audio.setAttribute('checked',enabled);
	
	},
	shutdown: function() {
		this.prefs.removeObserver("", this);
	},
	observe: function(subject, topic, data) {
     if (topic != "nsPref:changed") {
       return;
     }
 
     switch(data) {
       case "appearance.displaystatusbarpm_boolpref1":
      	if (swaksmack.SS_SBM == null) return;
       	var hid = this.prefs.getBoolPref("appearance.displaystatusbarpm_boolpref1");  
			  swaksmack.SS_SBM.hidePM(!hid);
         break;
       case "appearance.displaystatusbarlr_boolpref1":
      	if (swaksmack.SS_SBM == null) return;
       	var hid = this.prefs.getBoolPref("appearance.displaystatusbarlr_boolpref1");  
			  swaksmack.SS_SBM.hideLR(!hid);
         break;
       case "appearance.displaystatusbarkw_boolpref1":
      	if (swaksmack.SS_SBM == null) return;
       	var hid = this.prefs.getBoolPref("appearance.displaystatusbarkw_boolpref1");  
			  swaksmack.SS_SBM.hideKW(!hid);
         break;
       case "appearance.displaystatusbarsale_boolpref1":
      	if (swaksmack.SS_SBM == null) return;
       	var hid = this.prefs.getBoolPref("appearance.displaystatusbarsale_boolpref1");  
			  swaksmack.SS_SBM.hideSale(!hid);
         break;      
       case "audio.global_enable_boolpref":
       	var enabled = this.prefs.getBoolPref("audio.global_enable_boolpref");  
			 	var audio = document.getElementById('ss-sb-pu-audio');
				audio.setAttribute('checked',enabled);
         break;      
       case "usernamehl1_stringpref":
       	JF_usernamelistRegExp = null;
       	initUserNameArray(false); //highlightExistingComments(SS_doc);
         break;
       case "keywordshl1_stringpref":
       case "ignorecasehl_boolpref1":
       	JF_keywordlistRegExp = null;
       	JF_usernamelistRegExp = null;
       	highlightExistingComments(swaksmack.SmackShopDoc);
         break;
       case "ignore.ignorelist1_stringpref":
       case "ignore.ignorelist2_stringpref":
       case "ignore.ignorelistattend1_stringpref":
       	swaksmack.ignoreListCurrent = true;
       	JF_ignoreUserlistRegExp = null;
       	JF_ignoreWordlistRegExp = null;
       	JF_ignoreAttendancelistRegExp = null;
       	break;                              
     }
   }
   
}
window.addEventListener("load", function(e) { swaksmack.onLoad(e); }, false);

